#!/usr/bin/env python3
"""
用户系统完整使用示例
演示如何在代码中使用用户服务
"""

import asyncio
import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from src.database.database import AsyncSessionLocal
from src.service.user_service import UserService
from src.schemas.user import UserCreate, UserUpdate, UserListQuery


async def example_create_user():
    """示例：创建用户"""
    print("=== 创建用户示例 ===")
    
    async with AsyncSessionLocal() as db:
        # 创建用户数据
        user_data = UserCreate(
            username="example_user",
            password="password123",
            nick_name="示例用户",
            email="example@capcut.com",
            phone="13800138000",
            sex=1,
            remark="这是一个示例用户"
        )
        
        try:
            user = await UserService.create_user(db, user_data)
            print(f"用户创建成功: ID={user.id}, 用户名={user.username}")
            return user
        except ValueError as e:
            print(f"创建失败: {e}")
            return None


async def example_authenticate_user():
    """示例：用户认证"""
    print("\n=== 用户认证示例 ===")
    
    async with AsyncSessionLocal() as db:
        # 认证用户
        user = await UserService.authenticate_user(db, "admin", "admin123")
        
        if user:
            print(f"认证成功: {user.username}")
            
            # 生成访问令牌
            token = UserService.create_access_token({
                "user_id": user.id,
                "username": user.username
            })
            print(f"生成Token: {token[:50]}...")
            
            # 验证令牌
            payload = UserService.verify_token(token)
            if payload:
                print(f"Token验证成功: user_id={payload.get('user_id')}")
            
            return user
        else:
            print("认证失败")
            return None


async def example_update_user(user_id: int):
    """示例：更新用户信息"""
    print(f"\n=== 更新用户信息示例 (ID: {user_id}) ===")
    
    async with AsyncSessionLocal() as db:
        # 更新用户数据
        update_data = UserUpdate(
            nick_name="更新后的昵称",
            email="updated@capcut.com",
            avatar="http://example.com/avatar.jpg",
            remark="用户信息已更新"
        )
        
        try:
            updated_user = await UserService.update_user(db, user_id, update_data)
            if updated_user:
                print(f"用户更新成功: {updated_user.nick_name}")
            else:
                print("用户不存在")
        except Exception as e:
            print(f"更新失败: {e}")


async def example_get_user_list():
    """示例：获取用户列表"""
    print("\n=== 获取用户列表示例 ===")
    
    async with AsyncSessionLocal() as db:
        # 查询参数
        query = UserListQuery(
            page=1,
            page_size=5,
            username="",  # 不筛选用户名
            status=1      # 只查询正常状态用户
        )
        
        users, total = await UserService.get_user_list(db, query)
        
        print(f"总用户数: {total}")
        print("用户列表:")
        for user in users:
            print(f"  - ID: {user.id}, 用户名: {user.username}, 昵称: {user.nick_name}")


async def example_change_password():
    """示例：修改密码"""
    print("\n=== 修改密码示例 ===")
    
    async with AsyncSessionLocal() as db:
        # 获取测试用户
        user = await UserService.get_user_by_username(db, "test")
        if not user:
            print("测试用户不存在")
            return
        
        try:
            success = await UserService.change_password(
                db, user.id, "test123", "newpassword123"
            )
            
            if success:
                print("密码修改成功")
                
                # 验证新密码
                auth_user = await UserService.authenticate_user(db, "test", "newpassword123")
                if auth_user:
                    print("新密码验证成功")
                
                # 改回原密码
                await UserService.change_password(db, user.id, "newpassword123", "test123")
                print("密码已恢复")
            else:
                print("密码修改失败")
        except Exception as e:
            print(f"修改密码出错: {e}")


async def example_user_operations():
    """示例：用户基本操作"""
    print("\n=== 用户基本操作示例 ===")
    
    async with AsyncSessionLocal() as db:
        # 根据ID获取用户
        user = await UserService.get_user_by_id(db, 1)
        if user:
            print(f"根据ID获取用户: {user.username}")
        
        # 根据用户名获取用户
        user = await UserService.get_user_by_username(db, "admin")
        if user:
            print(f"根据用户名获取用户: {user.nick_name}")
        
        # 根据邮箱获取用户
        user = await UserService.get_user_by_email(db, "admin@capcut.com")
        if user:
            print(f"根据邮箱获取用户: {user.username}")


async def example_soft_delete():
    """示例：软删除用户"""
    print("\n=== 软删除用户示例 ===")
    
    async with AsyncSessionLocal() as db:
        # 首先创建一个临时用户
        temp_user_data = UserCreate(
            username="temp_user",
            password="temp123",
            nick_name="临时用户"
        )
        
        try:
            temp_user = await UserService.create_user(db, temp_user_data)
            print(f"创建临时用户: {temp_user.username}")
            
            # 删除用户
            success = await UserService.delete_user(db, temp_user.id)
            if success:
                print("用户软删除成功")
                
                # 尝试再次获取用户（应该获取不到）
                deleted_user = await UserService.get_user_by_id(db, temp_user.id)
                if deleted_user is None:
                    print("删除后无法获取用户，软删除生效")
            else:
                print("用户删除失败")
        except Exception as e:
            print(f"软删除示例出错: {e}")


async def main():
    """主函数"""
    print("🎯 用户系统完整使用示例")
    print("=" * 50)
    
    try:
        # 创建用户示例
        new_user = await example_create_user()
        
        # 用户认证示例
        auth_user = await example_authenticate_user()
        
        # 更新用户信息示例
        if auth_user:
            await example_update_user(auth_user.id)
        
        # 获取用户列表示例
        await example_get_user_list()
        
        # 修改密码示例
        await example_change_password()
        
        # 用户基本操作示例
        await example_user_operations()
        
        # 软删除示例
        await example_soft_delete()
        
        print("\n✅ 所有示例执行完成！")
        
    except Exception as e:
        print(f"❌ 示例执行出错: {e}")


if __name__ == "__main__":
    asyncio.run(main()) 